package com.ruoyi.bus.controller.front;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ruoyi.bus.domain.*;
import com.ruoyi.bus.service.*;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.framework.util.ShiroUtils;
import com.ruoyi.framework.web.domain.server.Sys;
import com.ruoyi.system.domain.SysUser;
import com.ruoyi.system.service.ISysUserService;
import com.ruoyi.util.TimeConversionUtil;
import com.ruoyi.websocket.ProductWebSocket;
import org.apache.catalina.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.io.IOException;
import java.lang.reflect.Method;
import java.util.List;

@Controller
@RequestMapping("/api/order")
public class FrontOrderController extends BaseController {
    @Autowired
    private IBaseOrderService baseOrderService;

    @Autowired
    private NoGenerateServlce noGenerateServlce;
    @Autowired
    private ISysUserService userService;

    @Autowired
    private IMessageService messageService;

    @Autowired
    private ITransInfoService transInfoService;
    @Autowired
    private ITransUnitService transUnitService;
    @Autowired
    private INetworkInfoService networkInfoService;

    /**
     * 查询寄件订单信息
     * flag == send  查询寄件信息  否则查询收件信息
     */
    @RequestMapping("/getList")
    @ResponseBody
    public TableDataInfo getList(String customerId){
        BaseOrder baseOrder=new BaseOrder();

        baseOrder.setReferCustomerId(customerId);

        startPage();
        List<BaseOrder> baseOrderList=baseOrderService.list(new QueryWrapper<>(baseOrder).ne("ORDER_STATUS","00").ne("ORDER_STATUS","10"));
        for(BaseOrder baseOrder1:baseOrderList){
            TransUnit unit=transUnitService.getOne(new QueryWrapper<>(new TransUnit().setTransId(baseOrder1.getTransId())));
            baseOrder1.setTransName(unit.getTransName());
        }

        return getDataTable(baseOrderList);
    }

    /**
     * 查询待支付订单信息
     */
    @RequestMapping("/getNoPayList")
    @ResponseBody
    public TableDataInfo getNoPayList(String customerId){
        BaseOrder baseOrder=new BaseOrder();
        baseOrder.setReferCustomerId(customerId);
        baseOrder.setOrderStatus("10");
        List<BaseOrder> baseOrderList=baseOrderService.list(new QueryWrapper<>(baseOrder));
        for(BaseOrder baseOrder1:baseOrderList){
            TransUnit unit=transUnitService.getOne(new QueryWrapper<>(new TransUnit().setTransId(baseOrder1.getTransId())));
            baseOrder1.setTransName(unit.getTransName());
        }
        return getDataTable(baseOrderList);
    }
    /**
     * 查询收件订单信息
     * 取收获的tel=当前登录人的tel(需要在前端获取电话号码权限)
     */
    @RequestMapping("/getAccepList")
    @ResponseBody
    public TableDataInfo getAccepList(String tel){
        BaseOrder baseOrder=new BaseOrder();
        baseOrder.setSCustTele(tel);
        return getDataTable(baseOrderService.list(new QueryWrapper<>(baseOrder)));
    }




    /**
     * 添加订
     * 单信息
     * 添加之后订单状态改为待支付
     * @param baseOrder
     * @return
     */
    @Transactional
    @RequestMapping("/add")
    @ResponseBody
    public BaseOrder addAndList(@RequestBody BaseOrder baseOrder){

        baseOrder.setOrderId(noGenerateServlce.getSeqNo("OR",7));
        baseOrder.setOrderStatus("10");
        //拆分出发出城市和接收城市
        String fAddr=baseOrder.getFCustAddr();
        String sAddr=baseOrder.getSCustAddr();
        baseOrder.setSCity(sAddr.split("/")[1]);
        baseOrder.setFCity(fAddr.split("/")[1]);
        baseOrderService.save(baseOrder);
        TransUnit unit=transUnitService.getOne(new QueryWrapper<>(new TransUnit().setTransId(baseOrder.getTransId())));
        baseOrder.setTransName(unit.getTransName());
        if(StringUtils.isNotEmpty(baseOrder.getNetworkId())){
            NetworkInfo networkInfo=networkInfoService.getOne(new QueryWrapper<>(new NetworkInfo().setNetworkId(baseOrder.getNetworkId())));

            baseOrder.setNetworkName(networkInfo.getNetworkName());
        }
        return baseOrder;
    }

    /**
     * 前端点击支付成功（后台将状态改为已支付；并通知相应的物流商订单信息）
     * @param id
     * @return
     */
    @RequestMapping("/payOrder")
    @ResponseBody
    public BaseOrder payOrder(String id) throws IOException {
        BaseOrder baseOrder=baseOrderService.getById(id);

        //设置订单状态为已支付;设置运单号
        baseOrder.setOrderStatus("20");
        baseOrder.setTransOrderId(noGenerateServlce.getSeqNo("Y",9));
        baseOrderService.saveOrUpdate(baseOrder);

        //如果是预约寄件的情况下发送消息
        if("10".equals(baseOrder.getOrderType())){
            //该订单选择的物流商
            String transId=baseOrder.getTransId();
            SysUser user=new SysUser();
            user.setReferTransUnit(transId);

            List<SysUser> users=userService.selectUserList(user);

            if(users.size()>0){
                for(SysUser user1:users){
                    Message message=new Message();
                    message.setMessageId(noGenerateServlce.getSeqNo("MS",8));
                    message.setMessagePerson(user1.getUserId().toString());
                    String infoContent="接收到新的订单，预约时间为："+baseOrder.getSubscribeStartTime()+"~"+baseOrder.getSubscribeEndTime();
                    //未读状态
                    message.setStatus("10");
                    message.setMessageContent(infoContent);
                    messageService.save(message);

                }
            }

        }




        return baseOrder;
    }

    /**
     *
     * @param transId
     * @return
     */
    @RequestMapping("/getByTransId/{transId}")
    @ResponseBody
    public BaseOrder selectOrderOne(@PathVariable("transId") String transId){
        TransInfo transInfo=transInfoService.getOne(new QueryWrapper<>(new TransInfo().setTransInfoId(transId)));

       BaseOrder baseOrder=new BaseOrder();
       baseOrder.setOrderId("OR00019");
       baseOrder=baseOrderService.getOne(new QueryWrapper<>(baseOrder));
        TransUnit unit=transUnitService.getOne(new QueryWrapper<>(new TransUnit().setTransId(baseOrder.getTransId())));
        baseOrder.setTransName(unit.getTransName());
        return baseOrder;
    }

    /**
     *
     * 取消订单
     * @param orderId
     * @return
     */
    @RequestMapping("/cancelOrder/{orderId}")
    @ResponseBody
    public AjaxResult cancelOrder(@PathVariable("orderId") String orderId){
        BaseOrder baseOrder=baseOrderService.getOne(new QueryWrapper<>(new BaseOrder().setOrderId(orderId)));
        baseOrder.setOrderStatus("00");
        return toAjax(baseOrderService.saveOrUpdate(baseOrder));
    }

    /**
     * 根据运单号查询订单信息
     * @param transId
     * @param customerId
     * @return
     */
    @RequestMapping("/selectOrderByTransId")
    @ResponseBody
    public AjaxResult selectOrderByTransId(String transId){
        BaseOrder baseOrder=baseOrderService.getOne(new QueryWrapper<>(new BaseOrder().setTransOrderId(transId)));
        //订单查询不到
        if(baseOrder==null){
            return AjaxResult.error();
        }
        TransUnit transUnit=transUnitService.getOne(new QueryWrapper<>(new TransUnit().setTransId(baseOrder.getTransId())));
        if(transUnit==null){
            return AjaxResult.error();
        }
        return AjaxResult.success(transUnit.getTransCode());
    }

    /**
     *
     * 完成订单
     * @param orderId
     * @return
     */
    @RequestMapping("/finishOrder/{transOrderId}")
    @ResponseBody
    public AjaxResult finishOrder(@PathVariable("transOrderId") String transOrderId){
        BaseOrder baseOrder=baseOrderService.getOne(new QueryWrapper<>(new BaseOrder().setTransOrderId(transOrderId)));
        baseOrder.setOrderStatus("90");
        return toAjax(baseOrderService.saveOrUpdate(baseOrder));
    }

}
